import React from 'react';
import {inject, observer} from 'mobx-react';
import QRCode from 'qrcode.react';

@inject('portalLoginStore')
@observer
class E9QRCode extends React.Component {
    constructor(props) {
        super(props)
    }

    componentDidMount() {
        const {portalLoginStore} = this.props;
        const {state = {}} = portalLoginStore;
        const {cacheAccount:loginId, langId} = state;
        portalLoginStore.getLoginForm({loginId, langId});

        this.getQRCode();
    }

    componentDidUpdate() {
        this.getQRCode();
    }

    componentWillUnmount() {
        window.clearInterval(this.scanInterval);
    }

    render() {
        const {portalLoginStore} = this.props;
        const {labelObj, state = {}} = portalLoginStore;
        const {loginSettingInfo = {}, qrcode} = state;
        const {loginForm = {}} = loginSettingInfo;

        const size = this.props.size || 180;
        const color = this.props.color || loginForm.color || '#fff';

        return (
            <div className="e9login-QRCode">
                <div className="e9login-QRCode-area">
                    {!!qrcode ? <QRCode value={qrcode.text} size={size} fgColor="#404549" bgColor="#eaeaea"/> : ''}
                </div>
                <div className="e9login-QRCode-describe" style={{color}}>{labelObj.qrcode}</div>
            </div>
        );
    }

    getQRCode() {
        const {portalLoginStore} = this.props;
        const {state = {}} = portalLoginStore;
        const {qrcode} = state;

        if (!!qrcode) {
            window.clearInterval(this.scanInterval);
            this.scanInterval = window.setInterval(this.scanQRCode.bind(this), 1000);
        }
    }

    scanQRCode() {
        const {portalLoginStore} = this.props;
        portalLoginStore.onQCLogin();
    }
}

export default E9QRCode;